package com.vit.springController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.vit.domain.User;
import com.vit.service.UserService;

/**
 * Controller for User
 * @author i80260
 * 
 */
@Controller
public class UserController{
	@Autowired
	private UserService userService;

	@RequestMapping(value = "/addUser", method = RequestMethod.GET)
	public ModelAndView addUser(@ModelAttribute("user")User user) {
		System.out.println("Inside Adduser page");
		return new ModelAndView("addUser", "user", new User());
	}

	@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
	public ModelAndView saveUser(@ModelAttribute("user") User user,BindingResult result, ModelMap model) 
	{
		ModelAndView modelAndView;
		System.out.println("Save user page.");
		boolean validateSuccess = validate(user, result);
		if (validateSuccess) 
		{
			try 
			{
				User savedUser = userService.saveUser(user);
				System.out.println("Saved user retrieved.");
				model.addAttribute("firstName", savedUser.getFirstName());
				model.addAttribute("lastName", savedUser.getLastName());
				model.addAttribute("address", savedUser.getContact().getAddress());
				model.addAttribute("phone", savedUser.getContact().getPhone());
				model.addAttribute("id", savedUser.getId());
				modelAndView = new ModelAndView("viewUser","user",savedUser);
			}
			catch (Exception exception) 
			{
				modelAndView = new ModelAndView("error");
				//modelAndView = new ModelAndView("addUser","user",user);
			}
		}
		else
		{
			 modelAndView = new ModelAndView("addUser","user",user);
		}
		return modelAndView;
	}

	/**
	 * 
	 * @param user
	 * @param result
	 * @return
	 */
	private boolean validate(User user, BindingResult result) {
		boolean validateSuccess = true;
		UserValidator userValidator = new UserValidator();
		userValidator.validate(user, result);
		if (result.hasErrors())
		{
			validateSuccess = false;
		}
		return validateSuccess;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}